<?php

namespace app\event;

use think\response\View;
use think\facade\Request;

class WriteHtml extends View
{

    public function handle($params)
    {
        self::HTML_FILE_NAME();
        $status = config('html.HTML_CACHE_ON');
        if ($status && !preg_match('/Status.*[345]{1}\d{2}/i', implode(' ', headers_list())) && !preg_match('/(-[a-z0-9]{2}){3,}/i', HTML_FILE_NAME)) {
            $params->content .= "\r\n<!--cacheTime:" . date("Y-m-d H:i:s") . "-->";
            $this->initStorage()->write(HTML_FILE_NAME, $params->content); //静态文件写入

        }
        // 事件监听处理
    }

    static function HTML_FILE_NAME()
    {
        $htmlPath = './Html/' . Request::App(true) . "/" . Request::controller(true) . "/" . Request::action(true);
        $rule = substr(md5(Request::url(true)), 0, 2);
        if (Request::query()) {
            define('HTML_FILE_NAME', $htmlPath . "/" . $rule . "/" . md5(Request::url(true)) . "." . config("route.url_html_suffix"));
        } else {
            define('HTML_FILE_NAME', $htmlPath . "." . config("route.url_html_suffix"));
        }
    }

    // 初始化模板编译存储器
    private function initStorage()
    {
        $class = '\\think\\template\\driver\\File';
        return new $class();
    }

}